package com.zb.framework.common.utlis;

import java.io.IOException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Locale;
import java.util.TimeZone;

import com.fasterxml.jackson.databind.DeserializationFeature;
import com.fasterxml.jackson.databind.ObjectMapper;

import org.apache.commons.lang3.StringUtils;

/**
 * jackson 工具类
 * 
 * @author liangfan
 * @date 2021/07/06 11:36
 **/
public class JsonUtils {

    private static final ObjectMapper MAPPER = initObjectMapper();

    /**
     * 初始化mapper
     * 
     * @author liangfan
     * @date 2021/7/6 14:09
     * @return com.fasterxml.jackson.databind.ObjectMapper
     */
    private static ObjectMapper initObjectMapper() {

        ObjectMapper objectMapper = new ObjectMapper();
        // 关闭字段不识别报错
        objectMapper.configure(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES, false);
        // 调整默认时区为北京时间
        TimeZone timeZone = TimeZone.getTimeZone("GMT+8");
        DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.CHINA);
        dateFormat.setTimeZone(timeZone);
        objectMapper.setDateFormat(dateFormat);
        objectMapper.setTimeZone(timeZone);
        return objectMapper;
    }

    /**
     * 反序列化
     * 
     * @author liangfan
     * @date 2021/7/6 14:09
     * @param str
     * @param clazz
     * @return T
     */
    public static <T> T toObject(String str, Class<T> clazz) {
        if (StringUtils.isBlank(str) || clazz == null) {
            return null;
        }

        T t = null;
        try {
            return clazz.equals(String.class) ? (T)str : MAPPER.readValue(str, clazz);
        } catch (IOException e) {
            e.printStackTrace();
        }
        return t;
    }

    /**
     * 反序列化
     * 
     * @author liangfan
     * @date 2021/7/6 14:06
     * @param str
     * @param clazz
     * @return T
     */
    public static <T> T toObj(String str, Class<T> clazz) throws IOException {
        if (StringUtils.isBlank(str) || clazz == null) {
            return null;
        }
        return clazz.equals(String.class) ? (T)str : MAPPER.readValue(str, clazz);
    }

    /**
     * 序列化
     * 
     * @author liangfan
     * @date 2021/7/6 14:04
     * @param obj
     * @return java.lang.String
     */
    public static <T> String toJsonStr(T obj) {
        if (obj == null) {
            return null;
        }

        try {
            return obj instanceof String ? (String)obj : MAPPER.writeValueAsString(obj);
        } catch (Exception e) {
            return null;
        }
    }
}
